package com.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.InetSocketAddress;
import java.net.URI;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class IpFilter implements GlobalFilter  {
    Map<String,Integer> count = new HashMap<>();
    Map<String, Date> time = new HashMap<>();
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String hostString = exchange.getRequest().getRemoteAddress().getHostString();

        URI uri = exchange.getRequest().getURI();
        String path = uri.getPath();

        if(path.indexOf("register")>-1){
            count.compute(hostString,(k,v)->{
                if(v == null){
                    return 1;
                }else {
                    return  v++;
                }
            });

            if(!time.containsKey(hostString)){
                time.put(hostString,new Date());
            }else {
                Date date = time.get(hostString);
                int minutes   = date.getMinutes();
                int minutes1 = new Date().getMinutes();
                if((minutes1 - minutes)>1){
                    count.remove(hostString);
                    time.put(hostString,new Date());
                }else {
                    Integer integer = count.get(hostString);
                    if(integer>100){
                        //拒绝访问
                        ServerHttpResponse response = exchange.getResponse();
                        response.setStatusCode(HttpStatus.UNAUTHORIZED); // 状态码
                        String data = "Request be denied!";
                        DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
                        return response.writeWith(Mono.just(wrap));
                    }
                }
            }
        }

        return chain.filter(exchange);
    }
}
